package com.javasm.adminapi.common.utils;

import com.alibaba.excel.EasyExcel;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @className: ExportUtil
 * @description:
 * @author: gfs
 * @date: 2025/10/9 16:36
 * @version: 0.1
 * @since: jdk17
 */
@Component
@Log4j2
public class ExportUtil<T> {
    @Resource
    HttpServletResponse response;

    public void exportExcel(List<T> list,Class<T> tClass){
        try {
            //设置导出的头信息
            response.setContentType("application/vnd.openxmlformates-officedocument.spreadsheetml.sheet");
            //字符集
            response.setCharacterEncoding("utf-8");
            //导出之后的文件名
            String fileName = URLEncoder.encode(RandomUtil.getFileName("demo.xlsx"), "UTF-8").replaceAll("\\+", "%20");
            //头信息
            response.setHeader("Content-Disposition","attachment;filename*=utf-8''"+fileName);
            //写出去
            EasyExcel.write(response.getOutputStream(),tClass).sheet().doWrite(list);
            //关闭流
            response.getOutputStream().close();
            ;
        } catch (IOException e) {
            log.error("导出Excel异常");
            throw new RuntimeException(e);
        }
    }
}
